/**输入任务的input框 */
import React, {useState, useRef} from 'react';
import './index.less';
import {Form, Input, Button} from 'antd';
import {connect} from 'react-redux';
import {add_new_task, get_day_task} from '../../redux/action/actions';

const CInput = (props) => {

  const form_ref = useRef(null);
  const input_ref = useRef(null);

  const [isFinish, setFinish] = useState(true); // 检查输入是否完成 默认显示输入完成 为了默认显示当天任务

  const onFinish = (value) => {
    props.add_new_task(value);
    setFinish(true);

    // 成功完成输入提交后，重置input输入框的值
    form_ref.current.resetFields(["inputValue"]);
    // 清空input值后，input自动获得焦点
    input_ref.current.focus();
  }

  if(isFinish) {
    let {bool} = props.add_new_task_reducer;  // 这一步不能放到onFinish函数里，因为需要先初始化执行一次
    if(bool && document.cookie) {
      props.get_day_task();
      setFinish(false);
    }
  }
  
  return (
    <div className="input_wrap">
      <Form
        ref={form_ref}
        name="createTask"
        onFinish={onFinish}
      >
        <Form.Item name="inputValue"  className="input">
          <Input 
            ref={input_ref} 
            autoComplete="off" 
            placeholder="please input your new task here." 
            />
        </Form.Item>
        <Form.Item className="button">
          <Button type="primary" htmlType="submit" >
            完成
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}

export default connect(
  state => state,
  {add_new_task, get_day_task}
)(CInput);
